﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Model;
using Model.Entities;
using log4net;

namespace CardDownloader
{
    public partial class FormMain : Form
    {
        private static readonly ILog log = LogManager.GetLogger(typeof (FormMain));
        public List<PageUrl> PageUrls { get; set; }
        public string FirstPageUrl { get; set; }
        private StringBuilder _builder;
        private event EventHandler<EventArgs> OnDownloadListPageUrlFinish;
        public bool IsOCG { get { return FirstPageUrl.Contains(Consts.OCG); } }
        public string DataDirectory { get { return IsOCG ? Consts.OCG_DATA_DIRECTORY : Consts.TCG_DATA_DIRECTORY; } }

        public FormMain()
        {
            InitializeComponent();
            Init();
        }

        private void Init()
        {
            PageUrls = new List<PageUrl>();
            FirstPageUrl = Consts.FIRST_PAGE_URL_OCG;
            _builder = new StringBuilder();
            OnDownloadListPageUrlFinish += FormMain_OnDownloadListPageUrlFinish;
            Disposed += FormMain_Disposed;
            Closed += FormMain_Closed;
        }

        void FormMain_Closed(object sender, EventArgs e)
        {
            try
            {
                bool isSaveDataToFileSuccessfull = Utils.SaveDataToFile(PageUrls, DataDirectory, Consts.PAGE_URLS_DATA_FILE_NAME);
                MessageBox.Show(isSaveDataToFileSuccessfull ? "Save Data To File Successfull" : "Save Data To File Fail");
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        void FormMain_Disposed(object sender, EventArgs e)
        {
            OnDownloadListPageUrlFinish -= FormMain_OnDownloadListPageUrlFinish;
        }

        void FormMain_OnDownloadListPageUrlFinish(object sender, EventArgs e)
        {
            if (InvokeRequired)
                BeginInvoke(new MethodInvoker(ProcessOnDownloadListPageUrlFinish));
            else
                ProcessOnDownloadListPageUrlFinish();
        }

        private void ProcessOnDownloadListPageUrlFinish()
        {
            try
            {
                dgvPageUrl.DataSource = PageUrls.Select(pu => new
                                                                  {
                                                                      Index = PageUrls.IndexOf(pu) + 1,
                                                                      pu.Name,
                                                                      pu.Status,
                                                                      CardCount = pu.CardInformations.Count
                                                                  }).ToList();
                lbStatus.Text = "Status: Download List Page Url Finish.";
                _builder.Insert(0, string.Format(Consts.LOG_FORMAT, DateTime.Now.ToString(Consts.DATETIME_FORMAT), "Download List Page Url Finish", Environment.NewLine));
                txtLog.Text = _builder.ToString();
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            try
            {
                var data = (List<PageUrl>)Utils.GetDataFromFile(Path.Combine(DataDirectory,Consts.PAGE_URLS_DATA_FILE_NAME));
                if (data != null)
                    PageUrls = data;
                dgvPageUrl.DataSource = PageUrls.Select(pu => new
                                                                  {
                                                                      Index = PageUrls.IndexOf(pu) + 1,
                                                                      pu.Name,
                                                                      pu.Status,
                                                                      CardCount = pu.CardInformations.Count
                                                                  }).ToList();
                txtFirstPageUrl.Text = FirstPageUrl;
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void btnGetListPageUrl_Click(object sender, EventArgs e)
        {
            lbStatus.Text = "Status: Downloading List Page Url ...";
            _builder.Insert(0, string.Format(Consts.LOG_FORMAT, DateTime.Now.ToString(Consts.DATETIME_FORMAT), "Start Download List Page Url", Environment.NewLine));
            txtLog.Text = _builder.ToString();
            Task.Factory.StartNew(DownloadListPageUrl);
        }

        private void DownloadListPageUrl()
        {
            try
            {
                PageUrls = Utils.DownloadListPageUrl(FirstPageUrl, IsOCG);
                if (OnDownloadListPageUrlFinish != null)
                    OnDownloadListPageUrlFinish(this, null);
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

    }
}
